<template>
  <div class="qup-full-page">
    <section v-show="!showDetail">
      <search-form
        :search-config="searchConfig"
        :label-width="110"
        class="query-form"
        @search="handleSearch"
        @visible-change="$refs.refTable.refreshTableHeight()"
      />
      <table-box
        ref="refTable"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        show-selection
        :off-set="0"
        @btnOperate="btnOperate"
        @selection-change="selectChange"
      >
        <el-table-column slot="before" fixed="left" label="序号" width="50" align="center" type="index" />
      </table-box>
    </section>
    <DetailPage
      v-if="showDetail"
      :row="selectRow"
      :page-show.sync="showDetail"
      :flag="detailFlag"
      @close="closeDetail"
    />
    <export-files
      :key="'export'+exportKey"
      title="导出"
      :visible.sync="showExport"
      :config="exportConf"
    />
  </div>
</template>
<script>
import { delRP, enableRP, disableRP } from '@/api/rewardsPunishment'
export default {
  components: {
    DetailPage: () => import('./components/routineDetail')
  },
  data() {
    return {
      showDetail: false,
      detailFlag: 'new',
      selectRow: {},
      searchConfig: [
        {
          label: '奖惩编码',
          prop: 'rewardPunishmentCode',
          type: 'text',
          placeholder: '',
          single: true,
          operator: 'like'
        }, {
          label: '奖惩名称',
          prop: 'rewardPunishmentName',
          type: 'text',
          placeholder: '',
          single: true,
          operator: 'like'
        }, {
          label: '客户编码',
          prop: 'customerCode',
          type: 'text',
          value: '',
          placeholder: '',
          operator: 'like'
        },
        {
          label: '客户名称',
          prop: 'customerName',
          type: 'text',
          operator: 'like'
        }, {
          label: '账号编码',
          prop: 'businessAccountCode',
          type: 'text',
          placeholder: '',
          operator: 'like'
        }, {
          label: '账号名称',
          prop: 'businessAccountName',
          type: 'text',
          placeholder: '',
          operator: 'like'
        }, {
          label: '所属办事处',
          prop: 'agencyName',
          type: 'dialog',
          value: '',
          placeholder: '办事处',
          config: {
            requestMethod: 'post', // 远程搜索请求方式:post,get;默认为get
            remote: true, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'name'
            }, // api返回数据默认字段
            multiple: false,
            selectData: []
          },
          dialogConfig: {
            title: '办事处',
            interfacePath: '/select-service/api/v1/organization/page',
            filtersRaw: [{ 'id': 'isOffice', 'property': 'isOffice', 'value': '1', 'operator': '=' }],
            setting: [
              { prop: 'code', title: '编码' },
              { prop: 'name', title: '名称' }
            ]
          }
        }, {
          label: '通报类别',
          prop: 'notificationType',
          type: 'select',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            remoteUrl: `/data-dict/api/v2/dictionary/CIRCULATE_TYPE`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        }, {
          label: '奖惩类别', // SHOP_REWARD_PUNISH_TYPE
          prop: 'rewardPunishmentCategory',
          type: 'select',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            remoteUrl: `/data-dict/api/v2/dictionary/SHOP_REWARD_PUNISH_TYPE`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        }, {
          label: '数据来源',
          prop: 'dataSource',
          type: 'select',
          config: {
            selectData: [
              {
                label: '全部',
                value: ''
              }, {
                label: 'BPM',
                value: 0
              }, {
                label: '手工创建',
                value: 1
              }
            ]
          }
        }, {
          label: '启用状态',
          prop: 'enable',
          type: 'radio',
          config: {
            selectData: [
              {
                label: '全部',
                value: ''
              }, {
                label: '启用',
                value: 1
              }, {
                label: '停用',
                value: 0
              }
            ]
          }
        }
      ],
      tableConfig: {
        hideSearchBar: true,
        sort: 'lastUpdateTime',
        order: 'desc',
        apiHeader: {
          'Permission-perCode': 'routine',
          'Permission-App': 'slm'
        },
        buttonGroupCode: 'default',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/rewardPunishmentRoutine/page`,
        pageSize: 20,
        tablePage: [20, 40, 60, 100],
        setting: [{
          prop: 'rewardPunishmentCode',
          label: '奖惩编码',
          className: 'btn-green',
          clickFun: (row) => {
            this.viewDetail(row)
          },
          isButton: true
        },
        {
          prop: 'rewardPunishmentName',
          label: '奖惩名称'
        },
        {
          prop: 'enable',
          label: '启用状态',
          formatData: ({
            enable
          }) => {
            if (enable === 1) return '启用'
            else return '停用'
          }
        },
        {
          prop: 'fileNumber',
          label: '文件编号'
        },
        {
          prop: 'fileName',
          label: '文件名称'
        },
        {
          prop: 'customerCode',
          label: '客户编码'
        },
        {
          prop: 'customerName',
          label: '客户名称'
        },
        {
          prop: 'businessAccountCode',
          label: '业务账号编码'
        },
        {
          prop: 'businessAccountName',
          label: '业务账号名称'
        },
        {
          prop: 'agencyName',
          label: '办事处名称'
        },
        {
          prop: 'agencyType',
          label: '办事处性质',
          propEnum: {
            domainCode: 'marketing',
            appCode: 'slm',
            dictTypeCode: 'OFFICE_NATURE'
          }
        },
        {
          prop: 'notificationType',
          label: '通报类别',
          propEnum: {
            domainCode: 'marketing',
            appCode: 'slm',
            dictTypeCode: 'CIRCULATE_TYPE'
          }
        },
        {
          prop: 'rewardPunishmentCategory',
          label: '奖惩类别',
          propEnum: {
            domainCode: 'marketing',
            appCode: 'slm',
            dictTypeCode: 'SHOP_REWARD_PUNISH_TYPE'
          }
        },
        {
          prop: 'rewardAmount',
          label: '奖励金额'
        },
        {
          prop: 'plannedPenaltyAmount',
          label: '计划处罚金额'
        },
        {
          prop: 'penaltyType',
          label: '处罚金额类型',
          propEnum: {
            domainCode: 'marketing',
            appCode: 'slm',
            dictTypeCode: 'FINE_TYPE'
          }
        },
        {
          prop: 'warehouseOccupancyFee',
          label: '库房占用费'
        },
        {
          prop: 'isDerate',
          label: '是否有减免',
          formatData: ({
            isDerate
          }) => {
            if (typeof (isDerate) === 'undefined') return ''
            if (isDerate === 1) return '是'
            else return '否'
          }

        },
        {
          prop: 'derateAmount',
          label: '减免金额'
        },
        {
          prop: 'actualPenaltyAmount',
          label: '实际扣款金额'
        },
        {
          prop: 'financeDate',
          label: '财务日期'
        },
        {
          prop: 'dataSource',
          label: '数据来源',
          formatData: ({
            dataSource
          }) => {
            if (typeof (dataSource) === 'undefined') return ''
            if (dataSource === 1) return '手工新增'
            else return 'BPM'
          }
        }],
        btnList: [{
          buttonName: '新增',
          optCode: 'add',
          outerFlag: true
        }, {
          buttonName: '编辑',
          optCode: 'edit',
          outerFlag: true
        }, {
          buttonName: '导出',
          optCode: 'export',
          outerFlag: true
        }, {
          buttonName: '启用',
          optCode: 'enable',
          outerFlag: true
        }, {
          buttonName: '停用',
          optCode: 'disable',
          outerFlag: true
        }, {
          buttonName: '删除',
          optCode: 'delete',
          outerFlag: true
        }]
      },
      tableSelected: [],
      otherFilters: [],
      showExport: false,
      exportKey: new Date().getTime(),
      exportConf: []
    }
  },
  methods: {
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.showDetail = true
          this.detailFlag = 'new'
          break
        case 'edit':
          this.editFn()
          break
        case 'export':
          this.exportFn()
          break
        case 'enable':
          this.switchFn(true)
          break
        case 'disable':
          this.switchFn(false)
          break
        case 'delete':
          this.delFn()
          break
        default:
          break
      }
    },
    viewDetail(row) {
      this.selectRow = row
      this.showDetail = true
      this.detailFlag = 'view'
    },
    editFn() {
      if (!this.singleJudge(this.tableSelected, '编辑', false)) {
        return
      }
      // 只有数据来源为“手工新增”的数据，才允许编辑
      if (!this.checkOut({ 'dataSource': 1 }, this.tableSelected)) {
        this.$message.warning('只允许编辑手工新增数据')
        return
      }
      this.selectRow = this.tableSelected[0]
      this.showDetail = true
      this.detailFlag = 'edit'
    },
    // 导出
    exportFn() {
      this.$set(this, 'exportConf', [{
        code: 'routine',
        name: '常规奖惩管理列表',
        dataApi: '/slm-admin/api/v1/rewardPunishmentRoutine/export?type=0',
        selectedRows: this.tableSelected,
        queryField: 'id',
        filtersRaw: this.otherFilters
      }, {
        code: 'exportTemplate',
        name: '常规奖惩管理模板',
        async: false,
        templateMethod: 'post',
        templateApi: '/slm-admin/api/v1/rewardPunishmentRoutine/export?type=1'
      }])
      this.exportKey = new Date().getTime()
      this.$nextTick(() => {
        this.showExport = true
      })
    },
    // 开关
    async switchFn(flag) {
      /**
       * 只能针对启用状态的数据停用；
       * 只能停用手工新增的数据；
       * 可批量操作；
       */
      if (!flag) { // 停用
        if (!this.singleJudge(this.tableSelected, '停用', false)) {
          return
        }
        if (!this.checkOut({ 'enable': 1, 'dataSource': 1 }, this.tableSelected)) {
          this.$message.warning('只允许停用手工新增的启用状态数据')
          return
        }
        this.loading = true
        try {
          const ids = this.tableSelected.map(item => item.id)
          const res = await disableRP(ids)
          if (res.success === 1) {
            this.$message.success('停用成功')
            this.$refs.refTable.initTableData('opCondition')
          } else {
            this.$message.warning(res.msg)
          }
          this.loading = false
        } catch (error) {
          this.loading = false
        }
      } else { // 启用
        if (!this.singleJudge(this.tableSelected, '启用', false)) {
          return
        }
        if (!this.checkOut({ 'enable': 0 }, this.tableSelected)) {
          this.$message.warning('只允许启用停用状态数据')
          return
        }
        this.loading = true
        try {
          const ids = this.tableSelected.map(item => item.id)
          const res = await enableRP(ids)
          if (res.success === 1) {
            this.$message.success('启用成功')
            this.$refs.refTable.initTableData('opCondition')
          } else {
            this.$message.warning(res.msg)
          }
          this.loading = false
        } catch (error) {
          this.loading = false
        }
      }
    },
    // 删除
    async delFn() {
      if (!this.singleJudge(this.tableSelected, '删除', false)) {
        return
      }
      if (!this.checkOut({ 'enable': 0 }, this.tableSelected)) {
        this.$message.warning('只允许删除停用状态的数据')
        return
      }
      this.loading = true
      try {
        const ids = this.tableSelected.map(item => item.id)
        const delRes = await delRP(ids)
        if (delRes.success) {
          this.$message.success('删除成功')
          this.$refs.refTable.initTableData('opCondition')
        } else {
          this.$message.warning(delRes.msg)
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    // 需要完善增加异常消息弹出
    checkOut(rules, selection) {
      if (!rules) return
      let res = true
      const result = selection.map(item => {
        const arr = []
        for (const key in rules) {
          const ele = rules[key]
          arr.push(item[key] === ele)
        }
        return arr
      })
      res = result.flat(Infinity).every(item => item === true)
      return res
    },
    closeDetail(flag) {
      this.showDetail = false
      if (flag) this.$refs.refTable.initTableData('opCondition')
    },
    selectChange(v) {
      this.tableSelected = v
    },
    handleSearch(params) {
      this.otherFilters = params.filtersRaw
      this.$nextTick(() => {
        this.$refs.refTable.initTableData('opCondition')
      })
    }
  }
}

</script>
<style scoped>
.query-form{
  margin-bottom:10px;
}
</style>
